#include <tsin/selector/ConfigSelector.hpp>

#include <tsin/library/SCDLInterpreter.hpp>
#include <tsin/util/Logger.hpp>
#include <dlfcn.h>

using namespace tsin;

ConfigSelector::ConfigSelector(Config &config)
        : config(config), moduleHandle(0)
{
}

Game *ConfigSelector::select()
{
        Game **games = 0, *game = 0;

        dlerror();
        moduleHandle = dlopen(config.file, RTLD_LAZY);
        if (moduleHandle != 0) {
                games = (Game **)dlsym(moduleHandle, "games");
                if (games == 0) {
                        twarn << "Symbol no found!\n";
                } else {
                        game = *games;
                }
                return game;
        }

        game = SCDLInterpreter::openSCDL(config.file);
        if (game)
                return game;

        twarn << "Open file \"" << config.file << "\" failed!\n";
        return 0;
}
